package com.noble.glamour.ui.setting;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.noble.glamour.R;
import com.noble.glamour.bean.center.update.UpgradeSource;
import com.noble.glamour.bean.center.user.detail.UserDetail;
import com.noble.glamour.bean.config.VideoVerifyBean;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.library.base.BaseActivity;
import com.noble.glamour.module.logic.baseui.custom.SimpleTipDialog;
import com.noble.glamour.module.logic.config.Constant;
import com.noble.glamour.module.logic.request.HttpResponse;
import com.noble.glamour.module.logic.request.RequestComplete;
import com.noble.glamour.module.util.PickerDialogUtil;
import com.noble.glamour.module.util.UIShow;
import com.noble.library.dir.DirType;
import com.noble.library.log.PSP;
import com.noble.library.log.PToast;
import com.suke.widget.SwitchButton;

/**
 * 设置页面
 */
public class SettingAct extends BaseActivity implements OnClickListener, RequestComplete {
    private TextView clear_cache;
    private SwitchButton setting_video, setting_voice, setting_msg;
    private Boolean Message_Status, videoStatus, audioStatus;        // false是开true是开

    private VideoVerifyBean videoVerifyBean;  // 音视频开关配置信息

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.f1_settings_layout);
        setBackView(getResources().getString(R.string.title_set));
        initView();
    }

    private void initView() {
        findViewById(R.id.setting_feedback).setOnClickListener(this);
        findViewById(R.id.setting_update).setOnClickListener(this);
        findViewById(R.id.setting_clear_cache).setOnClickListener(this);
        findViewById(R.id.setting_logoff).setOnClickListener(this);
        findViewById(R.id.setting_action).setOnClickListener(this);
        findViewById(R.id.setting_about).setOnClickListener(this);

        // 清楚缓存
        clear_cache = (TextView) findViewById(R.id.setting_clear_cache_tv);
        String cacheSize = DirType.getCacheSize(this);
        clear_cache.setText(cacheSize);
        initSwitchButton();
    }

    private void initSwitchButton() {
        videoVerifyBean = ModuleMgr.getCommonMgr().getVideoVerify();

        setting_video = (SwitchButton) findViewById(R.id.setting_video);
        setting_voice = (SwitchButton) findViewById(R.id.setting_voice);
        setting_msg = (SwitchButton) findViewById(R.id.setting_msg);

        // 是否新消息提醒
        Message_Status = PSP.getInstance().getBoolean(Constant.SETTING_MESSAGE, Constant.SETTING_MESSAGE_DEFAULT);
        setting_msg.setChecked(Message_Status);
        setVideoAndAudioStatus();
        onClickSwitchBtn();
    }

    /**
     * 开关音视频状态
     */
    private void setVideoAndAudioStatus() {
        // 视频开关
        videoStatus = videoVerifyBean.getBooleanVideochat();
        setting_video.setChecked(videoStatus);

        // 音频开关
        audioStatus = videoVerifyBean.getBooleanAudiochat();
        setting_voice.setChecked(audioStatus);
    }

    /**
     * 开关状态切换
     */
    private void onClickSwitchBtn() {
        // 视频
        setting_video.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked) {    // 开启时判断权限
                    if (validChange())
                        switchVideo();
                    return;
                }
                switchVideo();
                videoStatus = isChecked;
            }
        });

        // 音频
        setting_voice.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked) {    // 开启时判断权限
                    if (validChange())
                        switchVoice();
                    return;
                }
                switchVoice();
                audioStatus = isChecked;
            }
        });

        // 新消息提醒
        setting_msg.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                switchMsg();
            }
        });
    }

    private void switchVideo() {
        if (videoStatus) {
            videoStatus = false;
            videoVerifyBean.setVideochat(0);
        } else {
            videoStatus = true;
            videoVerifyBean.setVideochat(1);
        }
        ModuleMgr.getCommonMgr().setVideochatConfig(videoStatus, audioStatus, this);
    }

    private void switchVoice() {
        if (audioStatus) {
            audioStatus = false;
            videoVerifyBean.setAudiochat(0);
        } else {
            audioStatus = true;
            videoVerifyBean.setAudiochat(1);
        }
        ModuleMgr.getCommonMgr().setVideochatConfig(videoStatus, audioStatus, this);
    }

    private void switchMsg() {
        if (Message_Status) {
            Message_Status = false;
            PSP.getInstance().put(Constant.SETTING_MESSAGE, Message_Status);
        } else {
            Message_Status = true;
            PSP.getInstance().put(Constant.SETTING_MESSAGE, Message_Status);
        }
    }

    /**
     * 状态重置
     */
    private void resetSwitch() {
        setting_video.setChecked(videoStatus);
        setting_voice.setChecked(audioStatus);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.setting_feedback:// 意见反馈
                UIShow.showSuggestAct(this);
                break;
            case R.id.setting_update:// 软件更新
                ModuleMgr.getCommonMgr().checkUpdate(this, UpgradeSource.Setting, true);//检查应用升级
                break;

            case R.id.setting_action:// 活动相关
                UIShow.showActionActivity(this);
                break;
            case R.id.setting_clear_cache:// 清除缓存
                clearAppCache();
                break;
            case R.id.setting_logoff:// 退出登录
                PickerDialogUtil.showSimpleTipDialog(this, new SimpleTipDialog.ConfirmListener() {
                    @Override
                    public void onCancel() {
                    }

                    @Override
                    public void onSubmit() {
                        exitLogin();
                    }
                }, getResources().getString(R.string.dal_exit_content), getResources().getString(R.string.dal_exit_title), getResources().getString(R.string.cancel), getResources().getString(R.string.ok), true);
                break;
            case R.id.setting_about:
                UIShow.showAboutAct(this);
                break;
            default:
                break;
        }
    }

    /**
     * 开关音视频功能权限
     */
    public boolean validChange() {
        UserDetail userDetail = ModuleMgr.getCenterMgr().getMyInfo();
        //开启音、视频通话时，男性用户判断是否VIP
        if (userDetail.getGender() == 1 && !userDetail.isVip()) {
            PickerDialogUtil.showSimpleTipDialogExt(SettingAct.this, new SimpleTipDialog.ConfirmListener() {
                @Override
                public void onCancel() {
                    resetSwitch();
                }

                @Override
                public void onSubmit() {
                    resetSwitch();
                    UIShow.showOpenVipActivity(SettingAct.this);
                }
            }, getResources().getString(R.string.dal_vip_content), "", getResources().getString(R.string.cancel), getResources().getString(R.string.dal_vip_open), true, R.color.text_zhuyao_black);
            return false;
        }
        //开启音、视频通话时，女性用户判断是否视频认证
        if (userDetail.getGender() == 2) {
            if (videoVerifyBean.getStatus() == 0 || videoVerifyBean.getStatus() == 2) {
                PickerDialogUtil.showSimpleTipDialogExt(SettingAct.this, new SimpleTipDialog.ConfirmListener() {
                    @Override
                    public void onCancel() {
                        resetSwitch();
                    }

                    @Override
                    public void onSubmit() {
                        resetSwitch();
                        UIShow.showMyAuthenticationVideoAct(SettingAct.this, 0);
                    }
                }, getResources().getString(R.string.dal_auth_content), "", getResources().getString(R.string.cancel), getResources().getString(R.string.dal_auth_open), true, R.color.text_zhuyao_black);
                return false;
            } else if (videoVerifyBean.getStatus() == 1) {
                resetSwitch();
                PToast.showShort(getResources().getString(R.string.toast_under_review));
                return false;
            }
        }
        return true;
    }

    public void exitLogin() {
        clearUserInfo();
        setResult(200);
        finish();
    }

    public static void clearUserInfo() {
        // 清除当前登录的用户信息
        ModuleMgr.getLoginMgr().logout();
        ModuleMgr.getCenterMgr().clearUserInfo();
        ModuleMgr.getCommonMgr().clearIdCardVerifyStatusInfo();
        PSP.getInstance().put("addMsgToUserDate", null);
        PSP.getInstance().put("recommendDate", null);
    }

    public void clearAppCache() {
        final Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    PToast.showLong(getResources().getString(R.string.toast_clearcache_ok));
                    clear_cache.setText("0KB");
                } else {
                    PToast.showLong(getResources().getString(R.string.toast_clearcache_error));
                }
            }
        };
        new Thread() {
            public void run() {
                Message msg = new Message();
                try {
                    ModuleMgr.getCommonMgr().clearCache();
                    msg.what = 1;
                } catch (Exception e) {
                    e.printStackTrace();
                    msg.what = -1;
                }
                handler.sendMessage(msg);
            }
        }.start();
    }

    @Override
    public void onRequestComplete(HttpResponse response) {
        if (response.isOk()) {
            videoVerifyBean = ModuleMgr.getCommonMgr().getVideoVerify();
            setVideoAndAudioStatus();
        }
    }
}